//
//  UWOHttpService.m
//  basic
//
//  Created by Jack on 2016/12/14.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "UWOHttpService.h"
#import "AFNetworking.h"

@implementation UWOHttpService

static AFHTTPSessionManager *manager;
+ (void)initialize{
    
    manager=[AFHTTPSessionManager manager];
    //    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObjectsFromArray:@[@"text/html",@"text/json"]];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
}
+ (void)GET:(NSString *)URLString
 parameters:(id)parameters
    success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
    failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    
    [manager GET:[URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *responseStr=[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        NSString *newResponseStr = [responseStr  stringByReplacingOccurrencesOfString:@":null" withString:@":\"\""];
        
        NSData *data=[newResponseStr dataUsingEncoding:NSUTF8StringEncoding];
        
        id responseObj=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        success(task,responseObj);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(task,error);
    }];
}

+ (void)POST:(NSString *)URLString
  parameters:(id)parameters
     success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
     failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    
    AFHTTPSessionManager *manager_post=[AFHTTPSessionManager manager];
    manager_post.responseSerializer.acceptableContentTypes = [manager_post.responseSerializer.acceptableContentTypes setByAddingObjectsFromArray:@[@"text/html",@"text/json"]];
    [manager_post POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSError *error=nil;
        NSData *dataResponse=[NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:&error];
        
        if (error) {
            failure(nil,error);
            return;
        }
        NSString *responseStr=[[NSString alloc]initWithData:dataResponse encoding:NSUTF8StringEncoding];
        
        NSString *newResponseStr = [responseStr  stringByReplacingOccurrencesOfString:@"null" withString:@"\"\""];
        
        NSData *data=[newResponseStr dataUsingEncoding:NSUTF8StringEncoding];
        id responseObj=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        success(task,responseObj);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(task,error);
    }];
}
- (void)isHaveNetwork {
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态发生改变的时候调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                NSLog(@"WIFI");
                [[NSNotificationCenter defaultCenter]postNotificationName:@"networkOk" object:nil];
            }
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                NSLog(@"自带网络");
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"networkOk" object:nil];
            }
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
                
            {
                NSLog(@"没有网络");
                
                UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"您的网络好像存在问题，请检查后重试" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                
                [alertView show];
            }
                
                break;
                
            case AFNetworkReachabilityStatusUnknown:
                
            {
                NSLog(@"未知网络");
                
                UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"您的网络好像存在问题，请检查后重试" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                
                [alertView show];
                
                
            }
                break;
            default:
                break;
        }
    }];
    // 开始监控
    [mgr startMonitoring];
}

+ (void)UPLOAD:(NSString *)URLString parameters:(NSDictionary *)parameters image:(UIImage *)image progress:(void (^)(NSProgress *uploadProgress))progress success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
       failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *data=UIImageJPEGRepresentation(image, 0.5);
        
        [formData appendPartWithFileData:data name:@"qqfile" fileName:@"temp.jpg" mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        progress(uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *responseStr=[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *newResponseStr = [responseStr  stringByReplacingOccurrencesOfString:@":null" withString:@":\"\""];
        NSData *data=[newResponseStr dataUsingEncoding:NSUTF8StringEncoding];
        id responseObj=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        success(task,responseObj);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(task,error);
    }];
    
}
+ (void)UPLOAD:(NSString *)URLString parameters:(NSDictionary *)parameters imageArray:(NSArray *)imageArray progress:(void (^)(NSProgress *uploadProgress))progress success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
       failure:(void (^)(NSURLSessionDataTask * task, NSError *error))failure{
    
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (int i=0; i<imageArray.count; i++) {
            
            id imageData=imageArray[i];
            if ([imageData isKindOfClass:[UIImage class]]) {
                
                NSData *data=UIImageJPEGRepresentation(imageData, 0.5);
                NSString *imageName=[NSString stringWithFormat:@"temp_%02d.jpg",i+1];
                
                [formData appendPartWithFileData:data name:@"qqfile[]" fileName:imageName mimeType:@"image/jpeg"];
            }
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        progress(uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *responseStr=[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *newResponseStr = [responseStr  stringByReplacingOccurrencesOfString:@":null" withString:@":\"\""];
        NSData *data=[newResponseStr dataUsingEncoding:NSUTF8StringEncoding];
        id responseObj=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        success(task,responseObj);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(task,error);
    }];
}

@end
